#include "udpserver.h"

using namespace std;

UDPserver::UDPserver()
{

}

void UDPserver::socket(char *argv[])
{
    sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) error("Opening socket");
    length = sizeof(server);
    bzero(&server,length);
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=INADDR_ANY;
    server.sin_port=htons(atoi(argv[1]));
    // Enlazamos el socket a la dirección IP y puerto del servidor
    if (bind(sockfd,(struct sockaddr *)&server,length)<0)
        error("binding");
    fromlen = sizeof(struct sockaddr_in);
}

void UDPserver::checkConnection(int argc)
{
    if (argc != 2)
    {
        cout<<"ERROR, falta el puerto"<<endl;
        exit(0);
    }

}

void UDPserver::enviar(string buffer)
{
    bufferString2Char(buffer);
    n = sendto(sockfd,cbuffer,strlen(cbuffer),0,(struct sockaddr *)&from,fromlen);
    if (n  < 0) error("sendto");
}

void UDPserver::recibir()
{
    bzero(ccbuffer,1024);
    n = recvfrom(sockfd,ccbuffer,1024,0,(struct sockaddr *)&from,&fromlen);
    if (n < 0) error("recvfrom");
    bufferChar2String(ccbuffer);
}
